package netty5.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Created by GanJc on 2015/11/21.
 */
public class HttpFileServer {

    private static final Logger logger = LoggerFactory.getLogger(HttpFileServer.class);

    private static final String URL = "/src/main/java" ;

    public void run(String host , int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    socketChannel.pipeline().addLast(
                            new HttpRequestDecoder(),
                            new HttpObjectAggregator(65536),
                            new HttpResponseEncoder(),
                            new ChunkedWriteHandler(),
                            new HttpFileServerHandler(URL)
                    );
                }
            });
            ChannelFuture sync = b.bind(host,port).sync();
            logger.info("server 已启动,监听端口:{}:{}",host,port+URL);
            //等待服务端监听端口关闭
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new HttpFileServer().run("127.0.0.1",8888);
    }
}
